import { IBaseContentPage } from '@lib/IBaseIssuePage';
import { SSLib } from '@lib/SSLib';
import * as $ from 'jquery';
import './issuesPage.less';

export class IssuesPage implements IBaseContentPage {
    constructor() {
        ;
    }

    public IsMatch(url: string) {
        return /\/issues\/\d/.test(url);
    }

    public Execute() {
        init();

        bindReferenceIssues();

        bindCopy();

        bindTaskApply();
    }
}

let projectId;
let issueId = "";

function init() {
    let $btnCreateMergeDropdown = $('.create-merge-request-dropdown-toggle');
    $btnCreateMergeDropdown.click(e => {
        let $name = $('#source-name');

        $name.val('develop');

        setTimeout(() => {
            let evt = new CustomEvent('keyup', { detail: [2, 3, 4] });
            $name[0].dispatchEvent(evt);
        }, 200);
    });

    let projectName = "";
    projectId = $("#search_project_id").val();

    {
        let res = /\/([^\/]*?)\/issues\/(\d+)$/.exec(location.href);
        projectName = res[1];
        issueId = res[2];
    }
    bindRelatedMergeRequests();

    $('.btn-comment-and-close').attr('disabled', 'disabled').attr('title', '不允许在这里关闭议题，会出bug');
    $('.btn-close,.btn-reopen').each((index, item) => {
        item.addEventListener('click', closeIssue, true);
    });
}

function closeIssue(e) {
    if (!$(e.target).closest('.btn').hasClass('btn-close')) {
        return;
    }

    if (!canClose()) {
        e.preventDefault()
        e.stopPropagation();
    }

    function canClose() {
        if ($('.time-tracking-comparison-pane').length <= 0) {
            alert("estimate和spent不能为空");
            return false;
        }

        if ($('.due_date .no-value:not(.js-remove-due-date-holder)').length > 0) {
            alert("请设置到期时间 due date");
            return false;
        }

        return true;
    }
}

/**
 * 绑定合并请求的时间显示
 */
function bindRelatedMergeRequests() {
    let $relatedList = $('.related-items-list');
    let $items = $relatedList.find('.list-item');

    $relatedList.find('.score-slayer-spend').remove();

    SSLib.gGet(`/api/v4/projects/${projectId}/issues/${issueId}/related_merge_requests`, res => {
        let totalEs = 0;
        let totalSpend = 0;
        (res as any[]).forEach((item, index) => {
            let time_stats = item.time_stats;

            $items.eq(index).append(`
            <div class="score-slayer-spend">
              <span human_time_estimate>estimate:${time_stats.human_time_estimate}</span>
              <span human_total_time_spent>spent:${time_stats.human_total_time_spent}</span>
            </div>
            <div class="score-slayer-branch-merge">
              <span>${item.source_branch}->${item.target_branch}[${item.state}]</span>
            </div>`);
            totalEs += time_stats.time_estimate || 0;
            totalSpend += time_stats.total_time_spent || 0;
        });

        $('#merge-requests').find('.merge-requests-title').attr({totalEs, totalSpend}).append(`<div class="score-slayer-spend-total">totalEs: ${totalEs},totalSp:${totalSpend}</div>`);
    });

}

/**
 * 绑定引用议题 
 */
function bindReferenceIssues() {
    let $content = $('.detail-page-description .description');
    let $issues = $content.find('[data-reference-type="issue"]');

    if ($issues.length <= 0) {
        return;
    }

    let issuesData = $issues.map((index, item) => {
        let issueUrl = $(item).attr('href');

        try {
            let execResult = /\/([^\/]+?)\/issues\/(\d+)$/.exec(issueUrl);
            let project = execResult[1];
            let issueId = execResult[2];
            
            return {
                projectId: $(item).attr('data-project'),
                issueId,
                project
            };
        }
        catch (e) {
            console.error('插件报错');
            console.error(e);
        }
    }).get();

    let $title = $('.detail-page-description .title-container');

    let $referenceContainer = $('<div/>', { class : "slayer-reference-issue-container"});
    $title.before($referenceContainer);

    issuesData.forEach(item => drawReferenceIssueItem(item.project, item.projectId, item.issueId, $referenceContainer));
}

function drawReferenceIssueItem(project: string, projectId: string, issueId: string, $parent: JQuery) {
    SSLib.gGet(`/api/v4/projects/${projectId}/issues/${issueId}`, (data: IssueModel) => {
        let $link = $('<a/>', {
            class: "reference-issue-link",
            title: data.title,
            href: data.web_url,
            target: '_blank'
        });
        $link.text(project + '/' + data.title + `【${data.state}】`);

        let $item = $('<div/>', { class: "reference-issue-item" });
        $link.appendTo($item);

        {
            let $labels = $('<div/>', { class: "label-container" });
            data.labels.forEach(item => {
                let $label = $("<span/>", { class: "label-item" });
                $label.text(item);
                $labels.append($label);
            });
            $labels.appendTo($item);
        }

        {
            let $dueContainer = $(`<div class="due-container">due date: ${data.due_date}</div>`);
            $dueContainer.appendTo($dueContainer);

            let now = SSLib.dateFormatter(new Date(), 'yyyy-MM-dd');
            if (now >= data.due_date) {
                $dueContainer.addClass('text-danger');
            }
            if(data.assignees && data.assignees.length>0){
                $dueContainer.append(data.assignees[0].name);
            }
            $dueContainer.appendTo($item);
        }

        $parent.append($item);
    }); 
}

function bindCopy() {
    let $copy = $('<button type="button" class="btn btn-red" style="height: 31px;line-height: 13px;">SlayerCopy</button>');
    $('.js-issuable-edit').after($copy);

    $copy.click(item => {
        let content = "";
        content += location.href + "\r\n";
        content += $('.issue-details .title-container .title').text() + "\r\n";

        SSLib.CopyToClipboard(content);
    });
}


function bindTaskApply() {
    let $btn = $('<button type="button" class="btn btn-green" style="height: 31px;line-height: 13px;">TaskApply</button>');
    $('.js-issuable-edit').after($btn);

    $btn.click(item => {
        SSLib.gGet(`/api/v4/projects/${projectId}/issues/${issueId}`, (data: IssueModel) => {
            var postData = {
                "taskName": data.title,
                "issueUrl": data.web_url,
                "selfEstimated": data?.time_stats?.time_estimate
            };
            debugger;///
            SSLib.gitlabPost('http://intra.ofpanda.cn/api/pmspwt/task_apply/v1/task_apply/add', postData, res=>{
                alert(JSON.stringify(res, null,2));
            });
        });
    });
}

class IssueModel {
    public due_date: string;
    public title: string;
    public state: "opened" | "closed";
    public web_url: string;
    public time_stats: {
        time_estimate: number,
        total_time_spent: number,
        human_time_estimate: string,
        human_total_time_spent: string
    };

    public assignees: [{
        name: string,
        username: string
    }];
    public labels: string[];

    public milestone: {
        title: string,
        description: string
    };
}
